<?php

// form show page
require_once 'view/pub/forms/show.php';
require_once 'model/common/form.php';
require_once 'model/common/session.php';
require_once 'model/common/article.php';
require_once 'model/common/user.php';
require_once WACT_ROOT.'util/dataspace.inc.php';
require_once APP_ROOT . "model/common/site.php";

class FormShowPage extends PageController {

	var $form;
	var $form_id;


    function FormShowPage() {
        parent::PageController();

        $this->form = new FormController();

        $this->form->addChild('submit', new ButtonController(new Delegate($this, 'submit')));
        $this->form->addChild('clean', new ButtonController(new Delegate($this, 'clean')));
        $this->form->setDefaultChild('submit');

        $this->form->registerOnLoadListener(new Delegate($this, 'load'));

        $this->addChild('FeedbackForm', $this->form);
        $this->setDefaultChild('FeedbackForm');

        $this->registerOnActivateListener(new Delegate($this, 'guard'));

        $site_id = Site::getTemplateSiteID();
        $mytemplate = 'pub/forms/show.html';

        $mytemplate2 = 'pub/forms/thanks.html';


        $this->view =& new FormShowView($mytemplate, $this->form);
        $thanks_view = & new LayoutFormView($mytemplate2);

        $this->setDefaultView($this->view);
        $this->addView('success', WACT_DEFAULT_VIEW);
        $this->addView('notfound', WACT_DEFAULT_VIEW);
        //$this->addView('clean', new Handle('RedirectView', array('/')));
        $this->addView('clean', WACT_DEFAULT_VIEW);
        $this->addView('thanks', $thanks_view);

    }

    function guard(&$source, &$request, &$responseModel) {
    	$form_id = $request->getParameter('form_id');
    	if (!$form_id) $form_id = $request->getPostProperty('form_id');
    	if (!$form_id) $form_id = $responseModel->get('form_id');
    	if (!$form_id) $form_id = $this->form_id;
    	//print 'Form_id: '.$form_id;
    	//print_r( $request );
        if (!$form_id) {
            print "Form was not found ";
            return 'notfound';
        }

        // REMOVE IT IN PRODUCTION!!!
        //faked user
        //$user_id = 20;
        //$user_record =& User::getRecord($user_id);
        //Session::setUser($user_record);


        //faked article
        //$_SESSION['article_id'] = 6;
        // TO BE REMOVED
    }

    function load(&$source, &$request, &$responseModel) {
    	$form_id = $request->getParameter('form_id');
    	if (!$form_id) $form_id = $request->getPostProperty('form_id');
        if (!$form_id) $form_id = $responseModel->get('form_id');
        if (!$form_id) $form_id = $this->form_id;
    	//print 'Form_id: '.$form_id;
        $record =& FormModel::getRecord($form_id);
        if (is_null($record)) {
            return 'notfound';
        }

        $responseModel->merge($record->export());

        // prepare article
        $article_id = 0;
        if (isset($_SESSION['article_id'])) {
        	$article_id = $_SESSION['article_id'];
        }
        if ($article_id) {
        	$article_record =& Article::getRecord($article_id);
        	$headline = $article_record->get('headline');
        	//print 'article_id='. $article_id.$headline;
            $responseModel->set('article_headline', $headline);
        }


        //prepare user
        $user_id = 0;
        if (Session::isLogin()) {
        	$user_id = Session::getUserId();
        }
         if ($user_id) {
        	$user_record =& User::getRecord($user_id);
        	$username = User::getFullUserName($user_record);
        	$responseModel->set('username', $username);
        }

        //print_r($responseModel);

    }

    function clean(&$source, &$request, &$responseModel) {
    	$this->form_id = $responseModel->get('form_id');
        $responseModel->removeAll();
        $this->load($source, $request, $responseModel);
        return 'clean';
    }

     function submit(&$source, &$request, &$responseModel) {
        $this->form_id = $responseModel->get('form_id');
        $form_id = $this->form_id;
        $record =& FormModel::getRecord($form_id);
        if (is_null($record)) {
            return 'notfound';
        }
        $email_send = $record->get('email_send');
        $db_update =  $record->get('db_update');
        $emails =  $record->get('emails');
        $form_title = $record->get('title');

        // prepare article
        $article_id = 0;
        if (isset($_SESSION['article_id'])) {
        	$article_id = $_SESSION['article_id'];
        }
        if ($article_id) {
        	$article_record =& Article::getRecord($article_id);
        	$headline = $article_record->get('headline');
        }
        //prepare user
        $user_id = 0;
        if (Session::isLogin()) {
        	$user_id = Session::getUserId();
        }
         if ($user_id) {
        	$user_record =& User::getRecord($user_id);
        	$username = User::getFullUserName($user_record);
        }

        if ($db_update) {
        	$submission_ds =& new DataSpace();
        	$submission_ds->set('user_id',$user_id);
            $submission_ds->set('form_id',$form_id);
            $submission_ds->set('date',date("Y-m-d H:i"));
            $submission_ds->set('article_id',$article_id);
            $submission_ds->set('new',1);
            $submission_id = SubmissionForm::insertSubmission($submission_ds);
        }

        //scan response model fields
        $msg = '';
        $keys = $responseModel->getPropertyList();
        foreach ($keys as $mykey) {
            //print $mykey."<br>";
        	$value =  $responseModel->get($mykey);
        	if (is_array($value)) {
                $str_val = '';
        		foreach($value as $index=>$item) {
        		    if (!$index) $str_val .= ''.$item;
        			else $str_val .= ', '.$item;
        		}
                $value = $str_val;
        	}
        	// key format: name^id
        	$arr = explode('^',$mykey);
        	//print($arr);
        	if ($arr) {
        		if (count($arr) == 2) {
                	$name = $arr[0];  // field name
                	$id = $arr[1];    // field id

                	$field_record =& FormFieldModel::getRecord($id);
                	$field_title = $field_record->get('title');
                	$msg .=  ( $field_title.": ".$value."<br>" );
                	//print $mykey.": ".$value."<br>";
                	//print $msg;
                	// save to db
                	if ($db_update) {
                		$field_ds =& new DataSpace();
                        $field_ds->set('submission_id',$submission_id);
                        $field_ds->set('field_id',$id);
                        $field_ds->set('value',$value);
                		$sf_id = SubmissionFormField::insertSubmissionField($field_ds);
                	}

        		}
        	}
        }


        // save into db and send email


        if ($email_send) {
        	$subject = 'Feedback form '.$form_title.' submitted by user '. $username;
        	if ($article_id)   $subject .= ' about article '. $headline;

        	$recepients = $emails;
        	$body = 'The user '.$username.' message: <br> '. $msg;
        	//print 'subject: '. $subject.'<br>';
            //print 'body: '. $body.'<br>';
        	mail($recepients,$subject,$body);
        }



        // load thanks page
        $responseModel->import($record->export());
        $responseModel->set('msg',$msg);
        //
        //print_r($responseModel);
        return 'thanks';
    }



}


?>